<template>
  <div :class="{'mobile-create': showMobilePage}" class="create-invoice">
    <div class="form-box">
      <Title title="选择交接人员" style="padding-bottom: 32px"/>
      <el-form ref="editHandoverForm" :model="dataForm" :rules="formRules" :label-position="formAlign" label-width="85px">
        <el-row>
          <el-col :span="10">
            <el-form-item label="交接人" prop="handoverId" class="is-required">
              <el-select
                v-model="dataForm.handoverId"
                :filter-method="filterData"
                :append-to-body="true"
                :disabled="!hasRouteAuth('auth:handover:transferee')"
                filterable
                size="small"
                placeholder="选择交接人"
                popper-class="global-select-down"
                class="user-select filterableSelect remoteRequest1 width240"
                @change="changeHandoverId">
                <el-option
                  v-for="item in userList.items"
                  :key="item.id"
                  :label="item.userName + (item.jobNumber ? `（${item.jobNumber}）` : '')"
                  :value="item.id"/>
                <div v-if="userLoading" class="loading-container"><i class="el-icon-loading"/></div>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4" class="mobile-transfer">
            <div class="transfer-arrow">变更为</div>
          </el-col>
          <el-col :span="10">
            <el-form-item label="被交接人" prop="byTransferId" class="is-required">
              <el-select
                v-model="dataForm.byTransferId"
                :filter-method="filterData"
                :append-to-body="true"
                filterable
                size="small"
                placeholder="选择被交接人"
                popper-class="global-select-down"
                class="user-select filterableSelect remoteRequest1 width240"
                @change="changeByTransferId">
                <el-option
                  v-for="item in byTransferItems"
                  :key="item.id"
                  :label="`${item.userName}（${item.jobNumber}）`"
                  :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <Title title="选择交接内容" style="padding: 10px 0 16px"/>
      <el-collapse v-model="activeNames" style="min-height: 100px">
        <el-collapse-item name="0">
          <div slot="title" class="module-group-name">
            <i :class="activeNames.includes('0') ? 'el-icon-arrow-down' : 'el-icon-arrow-right'" />固定表单<span style="color: #999; font-weight: normal">({{ tableData.length }})</span>
          </div>
          <FilterInput
            ref="FilterToolRef"
            v-model="paramsObj"
            :filter-list="filterList"
            :show-advanced-filter="false"
            style="margin-bottom: 12px"
            show-search-btn
            @handelClick="queryClick"
            @queryEmpty="queryEmpty"/>
          <el-table
            v-loading="tableLoading"
            ref="transferTable"
            :data="tableData"
            tooltip-effect="dark"
            style="width: 100%"
            row-key="businessType"
            border
            @select="handleSelectRow"
            @select-all="handleSelectAll">
            <el-table-column
              :reserve-selection="true"
              type="selection"
              width="55" />
            <el-table-column width="120" align="left">
              <template slot="header" slot-scope="scope">
                <span style="color: #f56c6c;">*</span>
                <span class="label">模块</span>
              </template>
              <template slot-scope="scope">{{ scope.row.module }}</template>
            </el-table-column>
            <el-table-column align="left" min-width="200">
              <template slot="header" slot-scope="scope">
                <span style="color: #f56c6c;">*</span>
                <span class="label">交接内容</span>
              </template>
              <template slot-scope="scope">
                <el-checkbox-group v-model="scope.row.contentsIds" class="status-checkbox">
                  <el-checkbox
                    v-for="(item, index) in scope.row.transferContent"
                    :key="index + Date.now()"
                    :label="item.status"
                    :disabled="!(multipleSelection.includes(scope.row.businessType))"
                    @change="selContentId($event, item)">
                    <span>{{ item.name }}：</span>
                    <span :class="(item.ids.length - item.removeIds.length) > 0 ? 'red-num' : ''">{{ (item.ids.length - item.removeIds.length) }}</span> /
                    <span>{{ (item.ids && item.ids.length) ? item.ids.length : 0 }}</span>
                    <el-button
                      v-if="scope.row.businessType !== 12 && item.ids && item.ids.length > 0"
                      type="text"
                      style="margin-left: 10px;"
                      @click="openOrderDialog(item, scope.row)">查看明细</el-button>
                  </el-checkbox>
                </el-checkbox-group>
              </template>
            </el-table-column>
            <el-table-column min-width="180">
              <template slot="header" slot-scope="scope">
                <span style="color: #f56c6c;">*</span>
                <span class="label">交接角色</span>
              </template>
              <template slot-scope="scope">
                <el-checkbox-group v-model="scope.row.roleIds" class="role-checkbox" @change="selRoleType($event, scope.row)">
                  <el-checkbox
                    v-for="(item, index) in scope.row.roles"
                    :key="index"
                    :label="item.value"
                    :disabled="!(multipleSelection.includes(scope.row.businessType))">{{ item.label }}</el-checkbox>
                </el-checkbox-group>
              </template>
            </el-table-column>
            <el-table-column
              prop="remark"
              label="交接说明"
              width="350px"
              show-overflow-tooltip />
          </el-table>
        </el-collapse-item>
        <el-collapse-item name="1">
          <div slot="title" class="module-group-name">
            <i :class="activeNames.includes('1') ? 'el-icon-arrow-down' : 'el-icon-arrow-right'" />自定义表单<span style="color: #999; font-weight: normal">{{ `(${customLength})` }}</span>
          </div>
          <CustomTable ref="CustomTableRef" :handover-id="dataForm.handoverId" @emitGetCustomData="saveCustomData" @openCustomDialog="openCustomDialog"/>
        </el-collapse-item>
      </el-collapse>
    </div>
    <fixed-pagination>
      <div class="center">
        <el-button :loading="loading" type="primary" class="submit-btn" size="small" @click="toSave('editHandoverForm')">提交</el-button>
        <el-button type="info" class="back-btn" size="small" @click="toBack()">返回</el-button>
      </div>
    </fixed-pagination>
    <detailList
      ref="detailList"
      :head-data="headData"
      @handleClose="closeOrderDialog"/>
  </div>
</template>
<script>
import Title from '@/components/Title';
import detailList from '../components/detailList';
import CustomTable from '../components/customTable';
import { tableData } from '../data';
import { getTransfereeCount } from '@/api/user';
import { handoverAdd } from '@/api/handover';
import { getList } from '@/api/user';
import ElMessage from '@/utils/message';
import { hasRouteAuth } from '@/utils/permission';
import mobileCreate from '@/mixins/mobileCreate';
import handOver from '../mixin';

export default {
  components: { Title, detailList, CustomTable },
  mixins: [mobileCreate, handOver],
  data() {
    return {
      tableLoading: false,
      tableData: _.cloneDeep(tableData),
      dataForm: {
        handoverId: '',
        byTransferId: ''
      },
      formRules: {
        handoverId: [{ required: true, trigger: 'change', message: '请选择交接人' }],
        byTransferId: [{ required: true, trigger: 'change', message: '请选择被交接人' }]
      },
      selectUserName: '',
      userList: [],
      userLoading: false,
      loading: false,
      multipleSelection: [],
      selectionData: [],
      moduleRoleData: {
        0: [],
        2: [],
        3: [],
        4: [],
        5: [],
        6: [],
        7: [],
        8: [],
        9: [],
        10: [],
        11: [],
        12: [],
        13: [],
        14: []
      },
      dialogVisible: false,
      orderData: [],
      byTransferItems: [],
      headData: [],
      activeNames: '',
      customLength: 0,
      businessType: 0, // 表单类型
      detailRow: {
        transferContent: []
      }, // 需要查看明细的行
      paramsObj: {},
      filterList: [{ keyword: 'name', name: '模块名称', type: 'input', placeholder: '请输入模块名称' }],
      fixMultipleSelection: []
    };
  },
  created() {
    this.getUser(1, '', 1, true);
    this.dataForm.handoverId = this.$store.getters.id;
  },
  mounted() {
    const that = this;
    const SELECTWRAP_DOM = document.querySelector('.user-select .el-select-dropdown__wrap');
    if (SELECTWRAP_DOM) {
      SELECTWRAP_DOM.addEventListener('scroll', function() {
        const CONDITION = this.scrollHeight - this.scrollTop <= this.clientHeight;
        if (CONDITION) {
          that.userLoadMore();
        }
      });
    }
    window.remoteRequest('.remoteRequest1', this.filterData);
  },
  methods: {
    hasRouteAuth,
    changeHandoverId() {
      this.$refs.CustomTableRef.resetData();
      this.clearTableSelection();
      this.multipleSelection = [];
      this.paramsObj.name = '';
      this.tableData = _.cloneDeep(tableData);
    },
    changeByTransferId() {
      // 渠道订单、项目订单需要传递被交接人参数, v3.5.0
      for (let i = 0; i < this.selectionData.length; i++) {
        if ([7, 8].includes(this.selectionData[i].businessType)) {
          // 模块勾选
          const params = {
            handoverId: this.dataForm.handoverId,
            businessType: this.selectionData[i].businessType,
            transfereeId: this.dataForm.byTransferId
          };
          getTransfereeCount(params).then(res => {
            this.formatData(res, this.selectionData[i], this);
          }).catch(err => {
            console.log(err);
          });
        }
        break;
      }
    },
    // 获取交接人和被交接人的列表
    userLoadMore() {
      const userList = this.userList;
      const currentPage = userList.page;
      const isMax = userList.items.length >= userList.total;
      if (!isMax && !this.userLoading) {
        this.getUser(currentPage + 1, this.selectUserName);
      }
    },
    getUser(page = 1, userName = '', type = 1, create = false) {
      this.userLoading = true;
      getList(page, 15, { userName, type }).then(({ data }) => {
        this.userLoading = false;
        if (page > 1 && this.userList.items) {
          const concatList = this.userList.items.concat(data.items);
          data.items = concatList;
          this.userList = data;
        } else {
          this.userList = data;
          if (create) {
            this.userList.items.push({
              id: this.$store.getters.id,
              userName: this.$store.getters.userName,
              jobNumber: this.$store.getters.jobNumber
            });
          }
        }
        this.byTransferItems = data.items.filter(cur => {
          return !!cur.userStatus;
        });
      });
    },
    filterData(val) {
      if (val) {
        this.selectUserName = val;
        const userName = val;
        this.getUser(1, userName);
      }
    },
    toBack() {
      this.$router.push({
        name: 'userHandover'
      });
    },
    toSave(editHandoverForm) {
      this.$refs[editHandoverForm].validate((vaild) => {
        if (vaild) {
          this.toAdd();
        } else {
          if (!this.dataForm.byTransferId) {
            ElMessage.warning('请选择被交接人！');
          }
          return false;
        }
      });
    },
    toAdd() {
      if (this.dataForm.handoverId === this.dataForm.byTransferId) {
        ElMessage.warning('交接人与被交接人不可重复');
        return;
      }
      if (this.multipleSelection.length === 0 && this.$refs.CustomTableRef.mulIds.length === 0) {
        ElMessage.warning('请选择交接模块！');
        return;
      }
      let temp = [];
      if (this.multipleSelection.length > 0) {
        if (this.validate()) return;
        temp = this.tableData.filter(item => {
          return this.multipleSelection.includes(item.businessType);
        });
      }
      if (this.$refs.CustomTableRef && this.$refs.CustomTableRef.mulIds.length > 0) {
        if (this.$refs.CustomTableRef.validate(true)) return;
        const data = this.$refs.CustomTableRef.customFlowData;
        const multi = this.$refs.CustomTableRef.mulIds;
        temp = temp.concat(data.filter(item => {
          return multi.includes(item.formId);
        }));
      }
      // 都选中,整理参数
      temp.forEach(item => {
        item.recordDetail = item.transferContent.filter(cur => {
          return item.contentsIds.includes(cur.status);
        }).map(ele => {
          const ids = ele.ids.filter(cur => {
            return ele.removeIds.indexOf(cur) === -1;
          });
          let fieldInfo = [];
          if (ele.fieldInfo) {
            fieldInfo = ele.fieldInfo.filter(cur => {
              return ele.removeIds.indexOf(cur.id) === -1;
            });
          }
          return {
            status: ele.status,
            num: ids.length,
            ids,
            fieldInfo
          };
        });
        item.tempRoleData = item.roleData.filter(cur => {
          return item.roleIds.includes(cur.roleType);
        });
        item.tempRoleData.forEach(ele => {
          ele.contents = ele.contents.filter(current => {
            return item.contentsIds.includes(current.status);
          });
        });
      });
      const infos = temp.map(item => {
        return {
          businessType: item.businessType,
          roleData: item.tempRoleData,
          recordDetail: item.recordDetail,
          roleDetail: item.roleIds,
          formId: item.formId
        };
      });
      this.loading = true;
      handoverAdd({
        handoverId: this.dataForm.handoverId,
        transfereeId: this.dataForm.byTransferId,
        infos: infos
      }).then(res => {
        this.loading = false;
        res.code === 200 && ElMessage.success('操作成功');
        this.$router.push({
          name: 'handoverDetail',
          params: { id: res.data }
        });
      }).catch(err => {
        this.loading = false;
        console.log(err);
      });
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    clearTableSelection() {
      if (this.$refs.transferTable && this.$refs.transferTable.clearSelection) {
        this.$refs.transferTable.clearSelection();
      }
      this.multipleSelection = [];
    },
    handleSelectRow(selection, item) {
      this.fixMultipleSelection = selection;
      if (!this.dataForm.handoverId) {
        ElMessage.warning('请先选择交接人！');
        this.clearTableSelection();
        return;
      }
      // 渠道订单、项目订单需要传递被交接人参数, v3.5.0
      const isOrder = [7, 8].includes(item.businessType);
      if (isOrder && !this.dataForm.byTransferId) {
        ElMessage.warning('渠道订单或项目订单需要先选择被交接人！');
        this.clearTableSelection();
        return;
      }
      // 当前勾选的模块
      this.selectionData = selection;
      this.multipleSelection = selection.map(item => {
        return item.businessType;
      });
      if (!this.multipleSelection.includes(item.businessType)) {
        // 模块未勾选,模块后面取消勾选
        item.contentsIds = [];
        item.roleIds = [];
        item.transferContent.map(cur => {
          cur.ids = [];
          cur.removeIds = [];
        });
      } else {
        // 模块勾选
        const params = {
          handoverId: this.dataForm.handoverId,
          businessType: item.businessType
        };
        if (isOrder) {
          params.transfereeId = this.dataForm.byTransferId;
        }
        getTransfereeCount(params).then(res => {
          this.formatData(res, item, this);
        }).catch(err => {
          console.log(err);
        });
      }
    },
    handleSelectAll(val) {
      this.fixMultipleSelection = val;
      if (!this.dataForm.handoverId) {
        ElMessage.warning('请先选择交接人！');
        this.clearTableSelection();
        return;
      }
      const isOrder = val.some(item => {
        if ([7, 8].includes(item.businessType)) {
          return true;
        }
      });
      if (isOrder && !this.dataForm.byTransferId) {
        ElMessage.warning('渠道订单或项目订单需要先选择被交接人！');
        this.clearTableSelection();
        this.clearModuleSelect();
        return;
      }
      if (val) {
        // 勾选模块,后面交接内容和角色全选
        this.multipleSelection = val.map(item => {
          return item.businessType;
        });
        // 创建请求数组
        const promiseArr = [];
        val.forEach(item => {
          promiseArr.push(this.createPromise(item, false));
        });
        // 串行执行请求
        this.executePromise(promiseArr);
      }
      this.clearModuleSelect();
    },
    clearModuleSelect() {
      // 不勾选模块,模块后面取消勾选
      this.tableData.forEach(item => {
        if (!this.multipleSelection.includes(item.businessType)) {
          item.contentsIds = [];
          item.roleIds = [];
          item.transferContent.map(cur => {
            cur.ids = [];
            cur.removeIds = [];
          });
        }
      });
    },
    queryClick() {
      if (this.paramsObj.name) {
        this.tableData = this.tableData.filter(item => {
          return item.module.indexOf(this.paramsObj.name) !== -1;
        });
      } else {
        this.tableData = _.cloneDeep(tableData);
        if (this.fixMultipleSelection.length) {
          this.tableData.forEach(item => {
            if (this.fixMultipleSelection.find(i => i.businessType === item.businessType)) { this.handleSelectRow(this.fixMultipleSelection, item); }
          });
        }
      }
    },
    queryEmpty() {
      this.paramsObj = {};
      this.tableData = _.cloneDeep(tableData);
      if (this.fixMultipleSelection.length) {
        this.tableData.forEach(item => {
          if (this.fixMultipleSelection.find(i => i.businessType === item.businessType)) { this.handleSelectRow(this.fixMultipleSelection, item); }
        });
      }
    },
    openCustomDialog(val) {
      this.openOrderDialog(val.item, val.row);
    },
    openOrderDialog(val, row) {
      this.detailRow = row;
      const isCheck = row.contentsIds.includes(val.status);
      if (!isCheck) {
        // val.removeIds = val.ids;
        this.$set(val, 'removeIds', val.ids);
      }
      this.headData = this.getHeadData(row.businessType);
      this.$refs.detailList.initData(val, row, isCheck);
    },
    closeOrderDialog(val) {
      for (let i = 0; i < this.detailRow.transferContent.length; i++) {
        if (this.detailRow.transferContent[i].status === val.status) {
          this.detailRow.transferContent[i].removeIds = val.removeIds;
        }
        const removeIdsLen = this.detailRow.transferContent[i].removeIds.length;
        const index = this.detailRow.contentsIds.findIndex(item => item === this.detailRow.transferContent[i].status);
        if (index === -1 && removeIdsLen !== this.detailRow.transferContent[i].ids.length) {
          // 全部取消勾选再勾选，需要勾选外面的状态
          this.detailRow.contentsIds.push(this.detailRow.transferContent[i].status);
        }
        if (index !== -1 && removeIdsLen > 0 && this.detailRow.transferContent[i].ids.length === removeIdsLen) {
          // 全部取消勾选，需要取消外面的勾选状态
          this.detailRow.contentsIds.splice(index, 1);
        }
      }
    },
    getHeadData(type) {
      // 自定义表单
      if (type === 15) {
        return [
          { label: '流水号', property: 'sn' },
          { label: '创建人', property: 'creator' },
          { label: '创建时间', property: 'createTime', type: 'minute', millisecond: true }
        ];
      }
      const temp = this.tableData.filter(item => {
        return item.businessType === type;
      });
      return temp[0].headData || [];
    },
    saveCustomData(val) {
      this.customLength = val;
    }
  }
};
</script>
<style lang="scss" scoped>
.create-invoice {
  margin: 16px;
  background-color: #fff;
  padding: 24px 24px 50px 24px;
  min-height: calc(100vh - 100px);
  .width240 {
    width: 240px;
  }
  &::v-deep {
    .el-collapse, .el-collapse-item__header, .el-collapse-item__wrap {
      border: none;
    }
    .el-collapse-item__header {
      height: 32px;
    }
    .el-collapse-item__arrow {
      display: none;
    }
    .el-collapse-item__content {
      padding: 0 0 0 20px !important;
    }
    .select-input-component {
      height: 40px;
    }
  }
  .module-group-name {
    font-size: 14px;
    font-weight: bold;
    user-select: none;
    ::v-deep .el-icon-arrow-down:before {
      color: #AEB6C7
    }
  }
}
.loading-container {
  width: 100%;
  text-align: center;
  i {
    color: #999;
  }
}
.transfer-arrow{
  padding-left: 16px;
  line-height: 32px;
  font-size: 14px;
  color: #31CC9C;
  background: url('../../../../assets/setting/transfer.png');
  background-size: contain;
  background-repeat: no-repeat;
}
.el-checkbox{
  display: block;
  margin-bottom: 10px;
}
.el-table{
  .status-checkbox{
    &::v-deep{
      .el-checkbox {
        pointer-events: none;
      }
      .el-checkbox__input,.el-checkbox__label {
        pointer-events: all;
      }
      .el-checkbox__input.is-checked+.el-checkbox__label{
        color: #999;
      }
      .red-num{
        color: #FF4E5F;
      }
    }
  }
}
.mobile-create {
  .mobile-transfer {
    margin: 0 0 22px 85px;
  }
}
</style>
